const net = require("net");


const { on_set_rfid_judgment } = require('./utils/set-rfid-serial-port-2.cjs')

// 心跳时长
const heartbeatInterval = 1000;



// 用于存储的数据池

const connect = (config) => {
  const client = new net.Socket();


  const onContentClient = () => {
    client.connect(config.port, config.host, () => {
      console.log("connected");

      const maxTime = 1400
      const readTime = 350
      const stopTime = maxTime - readTime

      const onReadData = () => {
        portWrite(`A5 04 01 00 55 01`)
        // setTimeout(() => {
        //   portWrite(`A5 04 01 00 60 F6`)
        // }, readTime);
      }

      setInterval(onReadData, readTime + stopTime);

      // 十六进制字符串转字节数组
      function hexStringToByteArray(hex) {
        const bytes = [];
        for (let i = 0; i < hex.length; i += 2) {
          bytes.push(parseInt(hex.substr(i, 2), 16));
        }
        return new Uint8Array(bytes);
      }
      function portWrite(data) {
        console.log('portWrite')
        client.write(hexStringToByteArray(data.replace(/\s+/g, '')));
      }

      // 开始发送心跳
      // setInterval(() => {

      //   const onSend = (data) => {
      //     const buffer = Buffer.from(data, 'hex');
      //     client.write(buffer);
      //   }

      //   onSend("A50401005501")

      // }, heartbeatInterval);
    });
  };

  const dataPool = []

  client.on('data', (message, remote) => {

    dataPool.push(...message);
    parsePacket()
  });

  client.on("end", () => {
    console.log("Connection closed.");
    retryContent();
  });

  client.on("error", (err) => {
    console.error("Error occurred:", err);
    client.destroy(); // 销毁客户端
    retryContent();
  });



  function parsePacket() {
    // 从 dataPool 截取 A5 开头的
    const startIndex = dataPool.findIndex(data => data === 0xA5);
    if (startIndex === -1) {
      return;
    }
    const len = dataPool[startIndex + 1];
    const endIndex = startIndex + len + 1;
    // 根据长度截取数据,截取到后进行处理
    const packetData = dataPool.splice(startIndex, endIndex);

    if (packetData.length < 14) return

    // 计算校验和
    let calculatedCK = calculateCK(packetData.slice(0, -1));
    let receivedCK = packetData[packetData.length - 1];

    // 检查校验和是否匹配
    if (calculatedCK !== receivedCK) {
      // console.error('校验和错误');
      return;
    }


    const antennaNumber = packetData[7];
    if (antennaNumber === 0) return

    // 提取数据部分（如果有）
    const epc_data = packetData.slice(10, -5);
    function byteArrayToHexString(bytes) {
      const str = bytes.map(byte => byte.toString(16).padStart(2, '0')).join(' ');
      // 去除空格并大写
      return str.replace(/\s+/g, '').toUpperCase();
    }

    const rfid = byteArrayToHexString(epc_data);

    if (!rfid) return

    console.log('rfid', rfid);

    // const config = {
    //   host: '192.168.1.1',
    //   port: 4001
    // }


    const key = `${config.host}-${antennaNumber}`;
    const sendResult = {
      key,
      ip: config.host,
      port: config.port,
      antenna: antennaNumber,
      rfid: rfid,
    };



    on_set_rfid_judgment(sendResult)

    if (dataPool.length >= startIndex + 25) {
      console.log('再次执行')
      parsePacket()
    }

  }


  function calculateCK(buffer) {
    let sum = 0;
    for (let i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    return (~sum + 1) & 0xFF;
  }

  function retryContent() {
    setTimeout(onContentClient, 1000);
  }

  onContentClient();
};

// 防错工装配置
connect({
  host: "192.168.100.140",
  port: 2000,
});
// connect({
//   host: "192.168.100.32",
//   port: 4001,
// });
// connect({
//   host: "192.168.100.30",
//   port: 4001,
// });

// 添加一个监听器以优雅地处理程序退出，清除定时器
process.on("SIGINT", function () {
  console.log("\nGracefully shutting down from SIGINT (Ctrl-C)");
  process.exit();
});
